﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Caifu
{
	/// <summary>
	/// 
	/// </summary>
	public static class CaifuUtil
	{
		public static readonly TimeSpan Cache5Minutes = new TimeSpan(0, 5, 0);
		public static readonly TimeSpan Cache15Minutes = new TimeSpan(0, 5, 0);
		public static readonly TimeSpan Cache30Minutes = new TimeSpan(0, 5, 0);
		public static readonly TimeSpan Cache60Minutes = new TimeSpan(0, 5, 0);

		/// <summary>
		/// 获取缓存值。
		/// 如果缓存中不在，则从指定的委托方法中获取。
		/// </summary>
		/// <typeparam name="TResult">委托封装的方法的返回值类型</typeparam>
		/// <param name="key">缓存键</param>
		/// <param name="func">委托方法实例</param>
		/// <param name="duration">缓存持续时间</param>
		/// <returns></returns>
		public static TResult GetValueFromCache<TResult>(string key, Func<TResult> func, TimeSpan duration)
		{
			var obj = HttpRuntime.Cache.Get(key);
			if (obj == null)
			{
				obj = func();
				if (obj != null)
				{
					HttpRuntime.Cache.Insert(key, obj, null,
						DateTime.Now.Add(duration),
						System.Web.Caching.Cache.NoSlidingExpiration);
				}
			}
			return (TResult)obj;
		}

		/// <summary>
		/// 获取缓存值。
		/// 如果缓存中不在，则从指定的委托方法中获取。
		/// </summary>
		/// <typeparam name="T">委托封装的方法的参数类型</typeparam>
		/// <typeparam name="TResult">委托封装的方法的返回值类型</typeparam>
		/// <param name="key">缓存键</param>
		/// <param name="func">委托方法实例</param>
		/// <param name="arg">委托封装的方法的参数值</param>
		/// <param name="duration">缓存持续时间</param>
		/// <returns></returns>
		public static TResult GetValueFromCache<T, TResult>(string key, Func<T, TResult> func, T arg, TimeSpan duration)
		{
			var obj = HttpRuntime.Cache.Get(key);
			if (obj == null)
			{
				obj = func(arg);
				if (obj != null)
				{
					HttpRuntime.Cache.Insert(key, obj, null,
						DateTime.Now.Add(duration),
						System.Web.Caching.Cache.NoSlidingExpiration);
				}
			}
			return (TResult)obj;
		}

		/// <summary>
		/// 获取缓存值。
		/// 如果缓存中不在，则从指定的委托方法中获取。
		/// </summary>
		/// <typeparam name="T1">委托封装的方法的参数类型1</typeparam>
		/// /// <typeparam name="T2">委托封装的方法的参数类型2</typeparam>
		/// <typeparam name="TResult">委托封装的方法的返回值类型</typeparam>
		/// <param name="key">缓存键</param>
		/// <param name="func">委托方法实例</param>
		/// <param name="arg1">委托封装的方法的参数1值</param>
		/// /// <param name="arg2">委托封装的方法的参数2值</param>
		/// <param name="duration">缓存持续时间</param>
		/// <returns></returns>
		public static TResult GetValueFromCache<T1, T2, TResult>(string key, Func<T1, T2, TResult> func, T1 arg1, T2 arg2, TimeSpan duration)
		{
			var obj = HttpRuntime.Cache.Get(key);
			if (obj == null)
			{
				obj = func(arg1, arg2);
				if (obj != null)
				{
					HttpRuntime.Cache.Insert(key, obj, null,
						DateTime.Now.Add(duration),
						System.Web.Caching.Cache.NoSlidingExpiration);
				}
			}
			return (TResult)obj;
		}
	}
}
